#include "Packet.hpp"

namespace phx
{

Packet::Packet() : 
	mData()
{

}

void Packet::append(Int data)
{
	mData.append((char*)data, sizeof(Int));
}

void Packet::append(std::string &data)
{
	mData.append((char*)data.size(), sizeof(UInt));
	mData.append(data.c_str(), data.size());
}

bool Packet::extract(Int &copyTo)
{
	if(mData.size() > 0)
	{
		memcpy(&copyTo, mData.c_str(), sizeof(Int));
		mData.erase(0, sizeof(Int));
		return true;
	}
	return false;
}

bool Packet::extract(std::string &copyTo)
{
	if(mData.size() > 0)
	{
		UInt size = 0;
		memcpy(&size, mData.c_str(), sizeof(UInt));
		mData.erase(0, sizeof(UInt));

		copyTo.assign(mData.c_str(), size);
		mData.erase(0, size);
		return true;
	}
	return false;
}

Packet& Packet::operator<<(Int data)
{
	mData.append((char*)data, sizeof(Int));
	return *this;
}

Packet& Packet::operator<<(std::string &data)
{
	mData.append((char*)data.size(), sizeof(UInt));
	mData.append(data.c_str(), data.size());
	return *this;
}

Packet& Packet::operator>>(Int &copyTo)
{
	if(mData.size() > 0)
	{
		memcpy(&copyTo, mData.c_str(), sizeof(Int));
		mData.erase(0, sizeof(Int));
	}
	return *this;
}

Packet& Packet::operator>>(std::string &copyTo)
{
	if(mData.size() > 0)
	{
		UInt size = 0;
		memcpy(&size, mData.c_str(), sizeof(UInt));
		mData.erase(0, sizeof(UInt));

		copyTo.assign(mData.c_str(), size);
		mData.erase(0, size);
	}
	return *this;
}

void Packet::setData(const char *data, size_t size)
{
	mData = "";
	mData.append(data, size);
}

}